package com.xiaozhichao.javaapi.base.serializable;

import org.junit.Test;

import java.io.*;
import java.nio.file.Files;


public class SerializableTest {

    /**
     * 序列化为ser文件
     */
    @Test
    public void serializingTest(){
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            Welkin welkin = new Welkin(1,"xiaozhichao",29);
            fos = new FileOutputStream("C:\\Users\\xiaozhichao\\Desktop\\test.ser");
            oos = new ObjectOutputStream(fos);
            oos.writeObject(welkin);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if(oos != null){
                    oos.close();
                }
                if(fos != null){
                    fos.close();
                }
            } catch (Exception el) {
                el.printStackTrace();
            }
        }
    }

    /**
     * 反序列化为对象
     */
    @Test
    public void DeSerializingTest(){
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            File file = new File("C:\\Users\\xiaozhichao\\Desktop\\test.ser");
            if(file.exists()){
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                Welkin welkin = (Welkin)ois.readObject();
                System.out.println(welkin.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if(ois != null){
                    ois.close();
                }
                if(fis != null){
                    fis.close();
                }
            } catch (Exception el) {
                el.printStackTrace();
            }
        }
    }
}
